import requests
from flask import Blueprint, jsonify, request

from config import UA
from model.cluster import Cluster
from model.prom_sites import PromSites
from public.time_utils import get_range_ts

from blues.cluster import bp


@bp.route('/api/cluster/<cluster_id>/prom/query/')
def instant_query(cluster_id, query='', time=''):
    c = Cluster()
    cluster = c.find_by_id(cluster_id)

    query = request.args.get('query')
    time = request.args.get('time')
    dic = {"query": query, "time": time}

    # 调用prom apiserver
    url = cluster['prom'] + "/api/v1/query"
    headers = {"User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False, params=dic)
    print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''


@bp.route('/api/prom/list')
def get_prom_list():
    p = PromSites()
    pl = p.find_all()
    return jsonify({'code': 200, 'data': pl})


@bp.route('/api/prom/probe_endpoints_list')
def probe_endpoints_list_api():
    prom_id = request.args.get("prom_id")
    endpoints_list, message = probe_endpoints_list(prom_id)
    return jsonify({'code': 200, 'data': endpoints_list, 'message': message})


def probe_endpoints_list(prom_id):
    p = PromSites()
    endpoints_list = []
    message = ''

    if prom_id:
        prom = p.find_by_id(prom_id)
        url = prom["url"] + "/api/v1/query?query=probe_duration_seconds"
        try:
            res = requests.get(url).json()
            print(res)
            if res['status'] == 'success' and len(res['data']['result']) > 0:
                for i in res['data']['result']:
                    endpoints_list.append({"prom_id": prom['id'], "instance": i['metric']['instance']})
            else:
                message += url + str(res)
        except Exception as e:
            error = "调用 {} 出错：".format(url) + str(e)
            print(error)
            message += error
    if not prom_id:
        pl = p.find_all()
        for prom in pl:
            url = prom["url"] + "/api/v1/query?query=probe_duration_seconds"
            try:
                res = requests.get(url).json()
                print(res)
                if res['status'] == 'success' and len(res['data']['result']) > 0:
                    for i in res['data']['result']:
                        endpoints_list.append({"prom_id": prom['id'], "instance": i['metric']['instance']})
                else:
                    message += url + str(res)
            except Exception as e:
                error = "调用 {} 出错：".format(url) + str(e)
                print(error)
                message += error
    return endpoints_list, message


@bp.route('/api/v1/prom/query')
def query():
    prom_id = request.args.get('prom_id')
    query_str = request.args.get('query')
    params = {
        'query': query_str,
    }
    # 调用prom api
    p = PromSites()
    prom = p.find_by_id(prom_id)
    url = prom['url'] + "/api/v1/query"
    headers = {"User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False, params=params)
    # print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''


@bp.route('/api/v1/prom/query_range')
def queryRange():
    prom_id = request.args.get('prom_id')
    time_range = request.args.get('time_range')
    query_str = request.args.get('query')
    start, end = get_range_ts(time_range)
    step_dict = {
        "hour": 60,
        "day": 60 * 10,
        "week": 60 * 60
    }
    params = {
        'query': query_str,
        'start': start,
        'end': end,
        'step': step_dict[time_range],
    }
    # 调用prom api
    p = PromSites()
    prom = p.find_by_id(prom_id)
    url = prom['url'] + "/api/v1/query_range"
    headers = {"User-Agent": UA}
    response = requests.get(url=url, headers=headers, verify=False, params=params)
    # print(response.text)
    try:
        return response.json()
    except Exception as e:
        print(e)
        return ''
